﻿using System;
using System.Configuration.Install;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;

namespace ScottLane.MediaFeeder.Host
{
    /// <summary>
    /// 
    /// </summary>
    /// <remarks>
    /// http://www.switchonthecode.com/tutorials/creating-a-simple-windows-service-in-csharp
    /// http://www.codeproject.com/KB/WCF/WCFMultipleHosting.aspx
    /// </remarks>
    [RunInstaller(true)]
    public class WindowsServiceInstaller : Installer
    {
        public WindowsServiceInstaller()
        {
            ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();
            processInstaller.Account = ServiceAccount.User;
            serviceInstaller.ServiceName = "Media Feeder";
            serviceInstaller.DisplayName = "Media Feeder";
            serviceInstaller.Description = "Provides RSS feeds for all media on the PC.";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            Installers.Add(processInstaller);
            Installers.Add(serviceInstaller);
        }

        protected override void OnAfterInstall(System.Collections.IDictionary savedState)
        {
            base.OnAfterInstall(savedState);

            ServiceController service = new ServiceController("Media Feeder");

            try
            {
                service.Start();
                Process.Start("http://code.google.com/p/mediafeeder/wiki/InstallationGuide");
            }
            catch
            {
            }
        }

        protected override void OnBeforeUninstall(System.Collections.IDictionary savedState)
        {
            base.OnBeforeUninstall(savedState);

            try
            {
                // stop the service
                // todo - this fails?
                //ServiceController service = new ServiceController("Media Feeder");

                //if (service.CanStop)
                //{
                //    service.Stop();
                //}

                Process.Start("net stop \"Media Feeder\"");
            }
            catch
            {
            }
        }
    }
}
